﻿using AJWPFAdmin.Core.Enums;
using AJWPFAdmin.Core.ExtensionMethods;
using AJWPFAdmin.Core.HardwareSDKS.EQLED;
using AJWPFAdmin.Core.Models.EF.Tables;
using DocumentFormat.OpenXml.Drawing.Diagrams;
using Masuit.Tools;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AJWPFAdmin.Core.Models
{
    /// <summary>
    /// LED配置信息
    /// </summary>
    public class LEDConfig
    {
        public string[] EntranceTextArray { get; set; }
        public string[] ExitTextArray { get; set; }

        public string[] LEDEntranceTextArray { get; set; }
        public string[] LEDExitTextArray { get; set; }

        public List<EQLEDControlConfigModel> EQLEDs { get; set; }

        private static readonly object _locker = new object();

        public void Init()
        {
            EntranceTextArray ??= DefaultEntranceTextArray;
            // 这里为了兼容更新,需要额外判断, 之前是三个输入框, 现在新增了一个报警的输入框,所以要做适配
            if(EntranceTextArray.Length != 4)
            {
                var newArray = new string[4];
                EntranceTextArray.CopyTo(newArray,0);
                EntranceTextArray = newArray;
            }
            LEDEntranceTextArray ??= DefaultEntranceTextArray;
            if (LEDEntranceTextArray.Length != 4)
            {
                var newArray = new string[4];
                LEDEntranceTextArray.CopyTo(newArray, 0);
                LEDEntranceTextArray = newArray;
            }

            ExitTextArray ??= DefaultExitTextArray;
            if (ExitTextArray.Length != 4)
            {
                var newArray = new string[4];
                ExitTextArray.CopyTo(newArray, 0);
                ExitTextArray = newArray;
            }
            LEDExitTextArray ??= DefaultExitTextArray;
            if (LEDExitTextArray.Length != 4)
            {
                var newArray = new string[4];
                LEDExitTextArray.CopyTo(newArray, 0);
                LEDExitTextArray = newArray;
            }

            EQLEDs ??= new List<EQLEDControlConfigModel>();
        }


        public void DisplayToLEDs(
            LEDTextScene scene,
            Passageway passageway,
            ShippingRecord record,
            bool isCamera,
            string[] customerLines = null,
            Action<string> logTo = null,
            Func<string, string> customFormatHandle = null)
        {
            lock (_locker)
            {
                // EQ LED 发送文本
                StringBuilder eqLEDLogsBuilder = logTo != null ? new StringBuilder() : null;
                try
                {
                    eqLEDLogsBuilder?.AppendLine("开始准备发送文本至EQLED");

                    int x = 0;
                    int y = 0;
                    int height = 0;
                    var EQLEDMatchs = passageway != null
                        ? EQLEDs
                        .Where(p => p.PassagewayIds != null && p.PassagewayIds.Contains(passageway.Id)).ToList()
                        : EQLEDs;

                    if (EQLEDMatchs.Count == 0)
                    {
                        eqLEDLogsBuilder?.AppendLine($"未找到EQLED设备");
                        logTo?.Invoke(eqLEDLogsBuilder.ToString());
                        return;
                    }
                    foreach (var led in EQLEDMatchs)
                    {
                        if (led.ProgramId != -1)
                        {
                            EQLEDUtil.Try_User_DelAllProgram(led.CardAddress);
                        }

                        led.ProgramId = EQLEDUtil.Try_User_AddProgram(led.CardAddress);

                        var lines = FormatLEDTextArray(scene, passageway.Direction, record, isCamera,
                            customerLines, customFormatHandle);

                        height = led.LineHeight;
                        for (int i = 0; i < lines.Length; i++)
                        {
                            var lineNum = i + 1;
                            var lineConfigItem = led.LineConfigs.FirstOrDefault(p => p.LineNumber == lineNum);
                            var color = lineConfigItem?.FontColor ?? EQLEDFontColor.红色;
                            var fontSize = lineConfigItem?.FontSize ?? 12;

                            var txt = led.CreateText(lines[i], x, y, led.ScreenWidth,
                                height, color, fontSize);
                            //if ()
                            //{
                            //    eqLEDLogsBuilder.AppendLine($"EQLED设备 {led.CardAddress} 连接失败");
                            //    continue;
                            //}
                            eqLEDLogsBuilder?.AppendLine($"EQLED设备 {led.CardAddress} ProgramId:{led.ProgramId},x:{x},y:{y},w:{led.ScreenWidth},h:{height}");
                            var sucess = EQLEDSDK.User_AddText(led.CardAddress, ref txt, led.ProgramId) != -1;

                            if (sucess)
                            {
                                y += height;

                            }

                            var msg = sucess ? "成功" : "失败";

                            eqLEDLogsBuilder?.AppendLine($"EQLED设备 {led.CardAddress} 添加文本:{lines[i]} {msg}");

                            //EQLEDSDK.User_RealtimeDisConnect(led.CardAddress);
                        }

                        var sendSuccess = EQLEDSDK.User_SendToScreen(led.CardAddress) ? "成功" : "失败";
                        eqLEDLogsBuilder?.AppendLine($"EQLED设备 {led.CardAddress} 发送数据:{sendSuccess}");
                    }
                }
                catch (Exception e)
                {
                    eqLEDLogsBuilder?.AppendLine($"EQ LED 发送文本异常:{e.Message}:{e.StackTrace}");
                }

                logTo?.Invoke(eqLEDLogsBuilder.ToString());
            }
        }

        public string[] FormatLEDTextArray(LEDTextScene scene,
            PassagewayDirection direction,
            ShippingRecord record,
            bool isCamera,
            string[] customerLines = null,
            Func<string, string> customFormatHandle = null)
        {
            var tplIndex = (int)scene;

            var tplArray = direction == PassagewayDirection.进
                ? (isCamera ? EntranceTextArray : LEDEntranceTextArray)
                : (isCamera ? ExitTextArray : LEDExitTextArray);

            var defaultTplArray = direction == PassagewayDirection.进 ? LEDConfig.DefaultEntranceTextArray : LEDConfig.DefaultExitTextArray;

            var tpl = tplArray?.ElementAtOrDefault(tplIndex) ?? defaultTplArray.ElementAtOrDefault(tplIndex);

            var processArray = customerLines?.Any() == true
                ? customerLines
                : tpl.Split("\r\n", StringSplitOptions.RemoveEmptyEntries);

            for (var i = 0; i < processArray.Length; i++)
            {
                processArray[i] = FormatLEDText(processArray[i], record, scene, customFormatHandle);
            }

            return processArray;
        }
        public string FormatLEDText(string tpl,
            ShippingRecord record,
            LEDTextScene scene, Func<string, string> customFormatHandle = null)
        {
            if (string.IsNullOrWhiteSpace(tpl)) return string.Empty;

            if (tpl.Contains("[日期]"))
            {
                tpl = tpl.Replace("[日期]", record.CreateDate.ToString("yyyy年MM月dd日"));
            }
            if (tpl.Contains("[时间]"))
            {
                tpl = tpl.Replace("[时间]", record.CreateDate.ToString("HH时mm分"));
            }
            if (tpl.Contains("[车牌号]"))
            {
                tpl = tpl.Replace("[车牌号]", record.CarNo);
            }
            if (tpl.Contains("[排放标准]"))
            {
                tpl = tpl.Replace("[排放标准]", record.EmissionStandard.ToString());
            }
            if (tpl.Contains("[是否通行]"))
            {
                tpl = tpl.Replace("[是否通行]", scene == LEDTextScene.已通过 ? "通行" : "等待处理...");
            }

            if (tpl.Contains("[错误消息]"))
            {
                tpl = tpl.Replace("[错误消息]", string.IsNullOrWhiteSpace(record.SyncResult) || record.SyncResult.IgnoreCaseEqual("ok") ? "无" : record.SyncResult);
            }

            if (tpl.Contains("[货物]"))
            {
                tpl = tpl.Replace("[货物]", record.Direction == PassagewayDirection.进 ? record.InGoodsName : record.OutGoodsName);
            }
            if (tpl.Contains("[重量]"))
            {
                tpl = tpl.Replace("[重量]", record.Direction == PassagewayDirection.进 ? record.InGoodsVolume.ToString() : record.OutGoodsVolume.ToString());
            }
            if (customFormatHandle != null)
            {
                tpl = customFormatHandle(tpl);
            }
            return tpl;
        }

        public static readonly string[] DefaultEntranceTextArray
            = new string[] {
                "[日期]\r\n[时间]\r\n请扫码登记\r\n减速慢行",
                "[车牌号]\r\n[时间]\r\n请稍后",
                "[车牌号]\r\n[排放标准]\r\n减速慢行",
                "[车牌号]\r\n[错误消息]",
            };

        public static readonly string[] DefaultExitTextArray
            = new string[] {
                "[日期]\r\n[时间]\r\n请扫码登记\r\n减速慢行",
                "[车牌号]\r\n[时间]\r\n请稍后",
                "[车牌号]\r\n[排放标准]\r\n欢迎再来",
                "[车牌号]\r\n[错误消息]",
            };
    }
}
